package com.ytxg.health_management.ai.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.ytxg.health_management.controller.UserController;
import com.ytxg.health_management.healthModel.entity.HealthModelRecord;
import com.ytxg.health_management.healthModel.service.ModelService;
import com.ytxg.health_management.pojo.dto.UserDto;
import com.ytxg.health_management.pojo.entity.Result;
import com.ytxg.health_management.util.JWTUtils;
import com.ytxg.health_management.util.ResultCode;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.StreamingChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;


@RestController
public class AiController {
    private static final Logger log = LoggerFactory.getLogger(AiController.class);
    @Resource
    StreamingChatModel streamingChatModel;
    @Resource
    private OllamaChatModel ollamaChatModel;
    @Resource
    ChatModel chatModel;
    @Resource
    UserController userController;
    @Resource
    private ModelService modelService;
    @PostMapping(value = "/ai2")
    public Result<String> hello(@RequestBody String question) {
        log.info("AI提问:{}",question);
        String call = chatModel.call(question);
        log.info("AI回答:{}",call);
        return Result.success(call);
    }


    /**
     * 流式对话
     *
     * @return
     */
    @GetMapping(value="/ai",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> generateStream(@RequestHeader("Authorization") String token) {
        Result<UserDto> userDtoResult = userController.tokenAuth(token);
        if (userDtoResult.getCode() == ResultCode.USER_AUTH_FALL) {
            throw new RuntimeException("身份验证失败");
        }
        DecodedJWT verify = JWTUtils.verify(token);
        String username = verify.getClaim("username").asString();
        Result<List<HealthModelRecord>> modelRecord = modelService.getModelRecord(username);
        String message = "以下是一位用户的健康指标数组，不需要过多思考请简洁地给出合理建议，不要使用markdown格式：" + modelRecord.toString();
        Flux<String> stream = streamingChatModel.stream(message);
//        Prompt prompt = new Prompt(new UserMessage(message));
        return stream;
//        return ollamaChatModel.stream(prompt);
    }


}
